package com.mikufufu.blog.service.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson2.JSON;
import com.mikufufu.blog.model.entity.FriendLink;
import com.mikufufu.blog.model.excel.FriendLinkExcel;
import com.mikufufu.blog.service.FriendLinkService;
import com.mikufufu.blog.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class FriendLinkExcelListener extends AnalysisEventListener<FriendLinkExcel> {

    private final FriendLinkService friendLinkService;

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<FriendLinkExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public FriendLinkExcelListener(FriendLinkService friendLinkService) {
        this.friendLinkService = friendLinkService;
        set = friendLinkService.list().stream().map(FriendLink::getLogoUrl).collect(Collectors.toSet());
    }

    private static Set<String> set = new HashSet<>();

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param friendLinkExcel  one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param analysisContext  context
     */
    @Override
    public void invoke(FriendLinkExcel friendLinkExcel, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(friendLinkExcel));
        cachedDataList.add(friendLinkExcel);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!cachedDataList.isEmpty()){
            // 这里也要保存数据，确保最后遗留的数据也存储到数据库
            saveData();
        }
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        List<FriendLink> friendLinkList = cachedDataList.stream().filter(friendLinkExcel -> !set.contains(friendLinkExcel.getLogoUrl()))
                .map(friendLinkExcel -> {
                    FriendLink friendLink = BeanUtil.copy(friendLinkExcel, FriendLink.class);
                    friendLink.setStatus(0);
                    return friendLink;
                }).collect(Collectors.toList());
        log.debug("新增数据：{}", JSON.toJSONString(friendLinkList));
        friendLinkService.saveBatch(friendLinkList);
        log.info("存储数据库成功！");
    }
}
